<script setup lang="tsx">
import type { ConfModel } from '@/apis/model/conf'
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import { getConfApi, postEmailApi, updateConfApi } from '@/apis/modules/conf'
import { useVerifyCode } from '@/composables/useVerifyCode'
import { ModalHelper } from '@/utils/modal.helper'
import { emailValidate } from '@/utils/validate'
import { Message } from '@arco-design/web-vue'
import { isUndefined } from 'lodash-es'

const googleVerify = ref(false)
const loading = ref(false)
const { wait, time } = useVerifyCode()
const formState = reactive({
  address: '',
  port: undefined,
  send_name: '', // 发件人名称
  name: '', // 发件人邮箱
  password: '',
  email: '',
  send_name_current: '',
})
const formRef = ref<FormInstance>()
const emailVerifying = ref(false)

const emailBtnMsg = computed(() =>
  emailVerifying.value
    ? '发送中'
    : !wait.value
        ? '发送测试邮件'
        : `${time.value}S 重新发送`,
)
const rules: Record<string, FieldRule | FieldRule[]> = {
  address: [{ required: true, message: '请输入主机地址' }],
  port: [
    {
      required: true,
      validator: (value: any, callback: any) => {
        if (isUndefined(value)) {
          callback('请输入主机端口')
        }
        if (Number(value) > 65535) {
          callback('端口号最大为65535')
        } else {
          callback()
        }
      },
    },
  ],
  name: [
    {
      required: true,
      validator: (value, callback) => emailValidate(value, callback),
    },
  ],
  send_name_current: [{ required: true, message: '请输入发件人名称' }],
  email: [{ type: 'email', message: '邮箱格式错误' }],
  password: [
    {
      required: true,
      message: '请输入邮箱密码',
    },
    {
      required: true,
      validator: (value, callback) => passwordValidate(value, callback),
    },
  ],
}

async function handleVerifyEmail() {
  const res = await formRef.value?.validate()
  if (res)
    return
  emailVerifying.value = true
  try {
    await postEmailApi(formState)
    wait.value = true
  } finally {
    emailVerifying.value = false
  }
}
async function getBaseInfo() {
  // @ts-ignore
  return getConfApi({ type: 1 }).then((res: ConfModel) => {
    // @ts-ignore
    googleVerify.value = Number(res.base_conf?.google_verify ?? 1) === 1
  })
}
const btnLoading = ref<boolean>(false)
const MODULE_TYPE = 2

function handleSubmitSuccess() {
  formState.send_name = formState.send_name_current
  btnLoading.value = true
  updateConfApi({
    type: MODULE_TYPE,
    // @ts-ignore
    email_conf: formState,
  })
    .then(() => {
      Message.success('修改成功')
    })
    .finally(() => {
      btnLoading.value = false
    })
}

async function getConfigInfo() {
  loading.value = true
  // @ts-ignore
  return getConfApi({ type: MODULE_TYPE })
    .then((res: ConfModel) => {
      Object.assign(formState, res?.email_conf)
      formState.send_name_current = formState.send_name
    })
    .finally(() => {
      loading.value = false
    })
}
const google_verify_code = ref('')

function handleChange(v: boolean) {
  const statusText = v ? '开启' : '关闭'
  google_verify_code.value = ''
  ModalHelper.confirm(
    {
      title: `${statusText}谷歌验证码`,
      width: 480,
      maskClosable: false,
      content: () => (
        <div class="w-full flex flex-col space-y-2">
          <span class="text-xs leading-5">
            确定要
            {statusText}
            谷歌验证码吗？
            {statusText}
            后，所有管理员账号登录
            {v ? '' : '不'}
            需校验谷歌验证码。
          </span>
          <div>
            <a-input
              modelValue={google_verify_code.value}
              placeholder="请输入谷歌验证码"
              class="placeholder:text-xs"
              onUpdate:modelValue={val =>
                (google_verify_code.value = val as string)}
            />
          </div>
        </div>
      ),
    },
    () =>
      updateConfApi({
        type: 1,
        // @ts-ignore
        base_conf: {
          google_verify: v ? 1 : 2,
        },
        google_verify_code: google_verify_code.value,
      })
        .then(() => {
          googleVerify.value = v
          Message.success('修改成功')
        })
        .finally(() => {
          btnLoading.value = false
        }),
  )
}
onMounted(() => {
  Promise.all([getConfigInfo(), getBaseInfo()])
})
</script>

<template>
  <main-container :show-pagination="false">
    <div class="flex flex-col">
      <span class="text-sm font-bold leading-5 text-color-1">谷歌验证码配置</span>
      <span class="mb-2 mt-1 text-xs leading-5 text-color-3">启用谷歌验证后，登录管理后台需要校验谷歌验证码</span>
      <a-checkbox
        :model-value="googleVerify"
        class="pl-0!"
        @change="handleChange"
      >
        启用
      </a-checkbox>
    </div>
    <a-divider
      :margin="24"
      class="border-color-1!"
    />
    <div class="flex flex-col">
      <span class="text-sm font-bold leading-5 text-color-1">邮箱配置</span>
      <span class="mt-1 text-xs leading-5 text-color-3">用于用户邮箱注册、找回密码、资源告警等功能使用</span>
    </div>
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      class="mt-6 w-400px!"
      layout="vertical"
      @submit-success="handleSubmitSuccess"
    >
      <a-form-item
        field="address"
        asterisk-position="end"
        label="主机地址"
        hide-asterisk
      >
        <a-input
          v-model.trim="formState.address"
          :max-length="100"
          show-word-limit
          placeholder="请输入主机地址"
        />
      </a-form-item>
      <a-form-item
        field="port"
        asterisk-position="end"
        label="主机端口"
        hide-asterisk
      >
        <a-input-number
          v-model="formState.port"
          :max="65535"
          :min="1"
          :hide-button="true"
          :precision="0"
          placeholder="请输入主机端，例如: 25"
        />
      </a-form-item>
      <a-form-item
        field="name"
        asterisk-position="end"
        label="发件人邮箱"
        hide-asterisk
      >
        <a-input
          v-model="formState.name"
          :max-length="100"
          placeholder="请输入发件人邮箱，例如: example@domain.com"
        />
      </a-form-item>
      <a-form-item
        field="password"
        asterisk-position="end"
        label="邮箱密码"
        hide-asterisk
      >
        <a-input
          v-model="formState.password"
          :max-length="64"
          placeholder="请输入邮箱密码"
        />
      </a-form-item>
      <a-form-item
        field="send_name_current"
        asterisk-position="end"
        label="发件人名称"
        hide-asterisk
      >
        <div>
          <a-input
            v-model="formState.send_name_current"
            placeholder="请输入发件人名称"
            :max-length="20"
            show-word-limit
          />
        </div>
      </a-form-item>
      <a-form-item
        field="email"
        asterisk-position="end"
        label="邮箱测试"
      >
        <div class="w-[400px] flex flex-col">
          <div class="flex">
            <a-input
              v-model="formState.email"
              placeholder="请输入测试邮箱地址"
            />
            <a-button
              type="outline"
              class="ml-2 w-140px"
              :disabled="emailVerifying || wait || !formState.email"
              @click="handleVerifyEmail"
            >
              {{ emailBtnMsg }}
            </a-button>
          </div>
          <span class="pt-1 text-xs text-color-3">向您填写的测试邮箱发送测试邮件，收到测试邮件说明配置正确</span>
        </div>
      </a-form-item>
      <a-form-item class="submit-btn-form mb-0!">
        <a-button
          type="primary"
          html-type="submit"
          :loading="btnLoading"
          class="w-18"
        >
          保存
        </a-button>
      </a-form-item>
    </a-form>
  </main-container>
</template>

<style scoped lang="less">
.submit-btn-form {
  :deep(.arco-form-item-label-col) {
    @apply mb-0;
  }
}
</style>
